//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import type { LocalRepoInfo, LocalRepoTagInfo, LocalRepoBranchInfo, RemoteInfo, HeadInfo } from "@/api/local_repo";
import { list_repo_branch, list_repo_tag, list_remote, get_http_url } from "@/api/local_repo";
import { Button, Card, Checkbox, Form, List, message, Modal, Space, Table, Tag } from "antd";
import { open as shell_open } from '@tauri-apps/api/shell';
import type { ColumnsType } from 'antd/es/table';
import moment from "moment";
import { remove_branch, remove_tag } from "@/api/git_wrap";
import { USER_TYPE_ATOM_GIT, USER_TYPE_GIT_CODE, USER_TYPE_GITEE, USER_TYPE_INTERNAL, type USER_TYPE } from "@/api/user";
import { AtomGitIssueList } from "@/pages/Workbench/components/AtomGitList";
import { GitCodeIssueList } from "@/pages/Workbench/components/GitCodeList";
import { GiteeIssueList } from "@/pages/Workbench/components/GiteeList";


interface RemoveBranchModalProps {
    repoPath: string;
    branchName: string;
    onCancel: () => void;
    onOk: () => void;
}

const RemoveBranchModal = (props: RemoveBranchModalProps) => {
    const [force, setForce] = useState(false);

    const removeBranch = async () => {
        await remove_branch(props.repoPath, props.branchName, force);
        message.info("删除成功");
        props.onOk();
    };

    return (
        <Modal open title="删除分支" mask={false}
            okText="删除" okButtonProps={{ danger: true }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                removeBranch();
            }}>
            <Form>
                <Form.Item>
                    是否删除分支&nbsp;{props.branchName}&nbsp;?
                </Form.Item>
                <Form.Item label="强制删除">
                    <Checkbox checked={force} onChange={e => {
                        e.stopPropagation();
                        setForce(e.target.checked);
                    }} />
                </Form.Item>
            </Form>

        </Modal>
    );
}


export interface GitInfoProps {
    repo: LocalRepoInfo;
    headInfo: HeadInfo;
    userType: USER_TYPE;
    userToken: string;
}

const GitInfo = (props: GitInfoProps) => {
    const [branchList, setBranchList] = useState<LocalRepoBranchInfo[]>([]);
    const [tagList, setTagList] = useState<LocalRepoTagInfo[]>([]);
    const [remoteList, setRemoteList] = useState<RemoteInfo[]>([]);
    const [removeBranchName, setRemoveBranchName] = useState("");
    const [removeTagName, setRemoveTagName] = useState("");

    const [remoteSite, setRemoteSite] = useState<"" | "atomgit" | "gitcode" | "gitee">("");
    const [ownerName, setOwnerName] = useState("");
    const [repoName, setRepoName] = useState("");

    const calcOwnerAndReop = (url: string) => {
        let ownerAndRepoName = "";
        if (url.includes("@") && url.includes(":")) {
            const index = url.indexOf(":");
            ownerAndRepoName = url.substring(index + 1);
        } else if (url.startsWith("https://")) {
            const remain = url.substring("https://".length);
            const index = url.indexOf("/");
            if (index == -1) {
                return false;
            }
            ownerAndRepoName = remain.substring(index + 1);
        }
        const parts = ownerAndRepoName.split("/");
        if (parts.length == 2) {
            setOwnerName(parts[0]);
            if (parts[1].endsWith(".git")) {
                setRepoName(parts[1].substring(0, parts[1].length - 4));
            } else {
                setRepoName(parts[1]);
            }
            return true;
        }
        return false;
    };

    const checkRemoteSite = (remoteList: RemoteInfo[]) => {
        if (props.userToken == "") {
            return;
        }
        if (props.userType == USER_TYPE_INTERNAL) {
            return;
        }
        const remoteInfo = remoteList.find(item => item.name == "origin");
        if (remoteInfo == undefined) {
            return;
        }

        if (calcOwnerAndReop(remoteInfo.url) == false) {
            return;
        }


        if (props.userType == USER_TYPE_ATOM_GIT) {
            if (remoteInfo.url.startsWith("https://atomgit.com/")) {
                setRemoteSite("atomgit");
                return;
            }
            if (remoteInfo.url.includes("@atomgit.com:")) {
                setRemoteSite("atomgit");
                return;
            }
        } else if (props.userType == USER_TYPE_GITEE) {
            if (remoteInfo.url.startsWith("https://gitee.com/")) {
                setRemoteSite("gitee");
                return;
            }
            if (remoteInfo.url.includes("@gitee.com:")) {
                setRemoteSite("gitee");
                return;
            }
        } else if (props.userType == USER_TYPE_GIT_CODE) {
            if (remoteInfo.url.startsWith("https://gitcode.com/")) {
                setRemoteSite("gitcode");
                return;
            }
            if (remoteInfo.url.includes("@gitcode.com:")) {
                setRemoteSite("gitcode");
                return;
            }
        }
    };

    const loadBranchList = async () => {
        const tmpList = await list_repo_branch(props.repo.path);
        setBranchList(tmpList);
    };

    const loadTagList = async () => {
        const tmpList = await list_repo_tag(props.repo.path);
        setTagList(tmpList);
    };

    const loadRemoteList = async () => {
        const tmpList = await list_remote(props.repo.path);
        setRemoteList(tmpList);
        await checkRemoteSite(tmpList);
    };

    const removeTag = async () => {
        await remove_tag(props.repo.path, removeTagName);
        message.info("删除成功");
        setRemoveTagName("");
        await loadTagList();
    };

    const branchColumns: ColumnsType<LocalRepoBranchInfo> = [
        {
            title: "分支",
            width: 100,
            dataIndex: "name",
        },
        {
            title: "上游分支",
            width: 120,
            dataIndex: "upstream",
        },
        {
            title: "提交ID",
            width: 280,
            dataIndex: "commit_id",
        },
        {
            title: "提交内容",
            dataIndex: "commit_summary",
        },
        {
            title: "提交时间",
            width: 140,
            render: (_, row: LocalRepoBranchInfo) => moment(row.commit_time).format("YYYY-MM-DD HH:mm:ss"),
        },
        {
            title: "操作",
            width: 100,
            render: (_, row: LocalRepoBranchInfo) => (
                <>
                    {["main", "develop", "master"].includes(row.name) == false && row.name != props.headInfo.branch_name && (
                        <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }}
                            onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setRemoveBranchName(row.name);
                            }}>删除分支</Button>
                    )}
                </>
            ),
        }
    ];

    useEffect(() => {
        loadBranchList();
        loadTagList();
        loadRemoteList();
    }, []);

    return (
        <div style={{ height: "calc(100vh - 50px)", overflowY: "scroll" }}>
            {remoteSite != "" && (
                <Card title="远程工单列表" bordered={false} headStyle={{ fontSize: "16px", fontWeight: 700, backgroundColor: "#eee" }}>
                    {remoteSite == "atomgit" && (
                        <AtomGitIssueList userToken={props.userToken} ownerName={ownerName} repoName={repoName} />
                    )}
                    {remoteSite == "gitcode" && (
                        <GitCodeIssueList userToken={props.userToken} ownerName={ownerName} repoName={repoName} />
                    )}
                    {remoteSite == "gitee" && (
                        <GiteeIssueList userToken={props.userToken} ownerName={ownerName} repoName={repoName} />
                    )}
                </Card>
            )}
            <Card title="分支列表" bordered={false} headStyle={{ fontSize: "16px", fontWeight: 700, backgroundColor: "#eee" }}>
                <Table rowKey="name" dataSource={branchList} columns={branchColumns} pagination={false} />
            </Card>
            <Card title="服务器列表" bordered={false} headStyle={{ fontSize: "16px", fontWeight: 700, backgroundColor: "#eee" }}>
                <List rowKey="name" dataSource={remoteList} pagination={false}
                    renderItem={item => (
                        <List.Item>
                            <Space>
                                <div style={{ width: "80px" }}>{item.name}</div>
                                <a onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    shell_open(get_http_url(item.url));
                                }}>{item.url}</a>
                            </Space>
                        </List.Item>
                    )} />
                    xx
            </Card>
            <Card title="标记列表" bordered={false} headStyle={{ fontSize: "16px", fontWeight: 700, backgroundColor: "#eee" }}>
                <List rowKey="name" dataSource={tagList} pagination={false}
                    grid={{ gutter: 16 }}
                    renderItem={item => (
                        <List.Item>
                            <Tag closable={props.headInfo.tag_name != item.name} onClose={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setRemoveTagName(item.name);
                            }}>{item.name}</Tag>
                        </List.Item>
                    )} />
            </Card>
            {removeBranchName != "" && (
                <RemoveBranchModal repoPath={props.repo.path} branchName={removeBranchName} onCancel={() => setRemoveBranchName("")}
                    onOk={() => {
                        setRemoveBranchName("");
                        loadBranchList();
                    }} />
            )}
            {removeTagName != "" && (
                <Modal open title="删除标记" mask={false}
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoveTagName("");
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeTag();
                    }}>
                    是否删除标记&nbsp;{removeTagName}&nbsp;?
                </Modal>
            )}
        </div>
    );
};

export default GitInfo;